/**
* <p>Title: Environment.java</p>
* <p>Description: </p>
* <p>Copyright: </p>
* <p>Company: </p>
* @author du
* @date 2018年2月3日
* @version 1.0
*/
package com.ds.atops.core.runtime;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ds.atops.common.utils.StringUtils;

/**
 * 创建时间：2018年2月3日 上午11:51:14 项目名称：ds-sys-devops
 * 
 * @author du
 * @version 1.0
 * @since JDK 1.7 文件名称：Environment.java 类说明： 调起shell
 */
public class Environment {
	private static Log logger = LogFactory.getLog(Environment.class);

	private String workdir;
	
	
	public String execCMD(String[] command,String[] env) {
		String rs=null;
		try {
			File dir = null;
			if (null!=workdir) {
				dir=new File(workdir);
			}
			Process process = Runtime.getRuntime().exec(command, env, dir);
			// process = Runtime.getRuntime().exec(cmd);
			int status = process.waitFor();
			if (status != 0) {
				logger.error("Failed to call shell's command and the return status's is: " +status+"\n"+StringUtils.merge(StringUtils.arr2str(command)));
				return rs;
			}
			BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
			StringBuffer line = new StringBuffer();
			while (input.readLine() != null) {
				line.append("\t").append(input.readLine()).append("\n");				
			}
			input.close();
			rs=line.toString();
			logger.info("execCMD result:"+rs);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rs;
	}

	public String execScript(String script,String[] env) {
		String rs=null;
		try {
			File dir = null;
			if (null!=workdir) {
				dir=new File(workdir);
			}
			Process process = Runtime.getRuntime().exec(script, env, dir);
			// process = Runtime.getRuntime().exec(cmd);
			int status = process.waitFor();
			if (status != 0) {
				logger.error("Failed to call shell's command and the return status's is: " +status+"\n"+script);
				return rs;
			}
			BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
			StringBuffer line = new StringBuffer();
			while (input.readLine() != null) {
				line.append("\t").append(input.readLine()).append("\n");				
			}
			input.close();
			rs=line.toString();
			logger.info("execScript result:"+rs);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rs;
	}

	public String getWorkdir() {
		return workdir;
	}

	public void setWorkdir(String workdir) {
		this.workdir = workdir;
	}

	public static void main(String[] args) {
		Environment environment=new Environment();
		environment.setWorkdir("d:\\");
		String sh="d:\\test.bat";
		String[] cmd= {"cmd","/C","dir"};
		environment.execScript(sh, null);
		//environment.execCMD(cmd, null);
	}
}
